package su.theravada.jpalireader.openBookDlg;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import su.theravada.jpalireader.MainWindow;
import su.theravada.jpalireader.PaliComboBox;
import su.theravada.jpalireader.entities.NodeInfo;
import su.theravada.jpalireader.entities.SearchMode;
import su.theravada.jpalireader.util.PaliUtil;
import su.theravada.jpalireader.util.SqlUtil;
import su.theravada.jpalireader.util.UTF8Control;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class OpenBookDlgTab2 extends javax.swing.JPanel {
	private JTextField ctlNameField;
	private JTextArea ctlItemPath;
	private PaliComboBox ctlPaliCombo;
	private JLabel ctlNoMatch;
	private JCheckBox ctlIgnoreDiac;
	private JButton ctlFind;
	private JComboBox ctlSearchMode;
	private JList ctlFoundNodes;
	private JScrollPane scrollPane; 

	public OpenBookDlgTab2() {
		super();
		initGUI();
	}
		
	private void initGUI() {
		try {
            ResourceBundle res_strings = ResourceBundle.getBundle("strings", Locale.getDefault(),new UTF8Control());
            
			this.setPreferredSize(new java.awt.Dimension(431, 277));
			this.setLayout(null);
			{
				ctlNameField = new JTextField();
				this.add(ctlNameField);
				ctlNameField.setBounds(6, 7, 197, 22);
			}
			{
				ctlFoundNodes = new JList();
				ctlFoundNodes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
				scrollPane= new JScrollPane();
				this.add(scrollPane);
				scrollPane.getViewport().setView(ctlFoundNodes);
				scrollPane.setBounds(6, 57, 345, 155);
			}
			{
	            
				ComboBoxModel ctlSearchModeModel = 
					new DefaultComboBoxModel(
							new SearchMode[] { 
									new SearchMode(res_strings.getString("Contains"),1), 
									new SearchMode(res_strings.getString("BeginsWith"),2) });
				
				ctlSearchMode = new JComboBox();
				this.add(ctlSearchMode);
				ctlSearchMode.setModel(ctlSearchModeModel);
				ctlSearchMode.setBounds(252, 6, 93, 22);
			}
			{
				ctlFind = new JButton();
				this.add(ctlFind);
				ctlFind.setText(res_strings.getString("Find"));
				ctlFind.setBounds(351, 7, 80, 22);
				ctlFind.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						ctlFindActionPerformed(evt);
					}
				});
			}
			{
				ctlIgnoreDiac = new JCheckBox();
				this.add(ctlIgnoreDiac);
				ctlIgnoreDiac.setText(res_strings.getString("IgnorePaliDiac"));
				ctlIgnoreDiac.setBounds(6, 33, 214, 19);
			}
			{
				ctlItemPath = new JTextArea();
				this.add(ctlItemPath);
				ctlItemPath.setBounds(6, 223, 414, 42);
				ctlItemPath.setWrapStyleWord(true);
				ctlItemPath.setLineWrap(true);
				ctlItemPath.setOpaque(false);
				ctlItemPath.setEditable(false);
				ctlItemPath.setFocusable(false);
			}
			{
				ctlPaliCombo = new PaliComboBox();
				this.add(ctlPaliCombo);
				ctlPaliCombo.setBounds(209, 6, 37, 22);
				ctlPaliCombo.setTextField(ctlNameField);
			}
			{
				ctlNoMatch = new JLabel();
				this.add(ctlNoMatch);
				ctlNoMatch.setBounds(226, 35, 200, 17);
				ctlNoMatch.setForeground(new java.awt.Color(255,0,0));
				ctlNoMatch.setText(res_strings.getString("NoMatches"));
				ctlNoMatch.setVisible(false);
			}

			ctlFoundNodes.addListSelectionListener(new ListSelectionListener()
			{
				@Override
				public void valueChanged(ListSelectionEvent arg0) {
					ListItemSelected(arg0);					
				}					
			});
			
			ctlNameField.addKeyListener(new KeyListener() {
				@Override
				public void keyPressed(KeyEvent arg0) {}

				@Override
				public void keyReleased(KeyEvent arg0) {
					if(arg0.getKeyCode()==KeyEvent.VK_ENTER)
						ctlFindActionPerformed(null);
				}

				@Override
				public void keyTyped(KeyEvent arg0) {}		
			});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void ListItemSelected(ListSelectionEvent arg0)
	{
		NodeInfo objSelNode=(NodeInfo)ctlFoundNodes.getSelectedValue();
		if(objSelNode==null)
			ctlItemPath.setText("");
		else
			ctlItemPath.setText(objSelNode.getPath());		
	}
	
	private void ctlFindActionPerformed(ActionEvent evt) {
		//System.out.println("ctlFind.actionPerformed, event="+evt);
		ctlItemPath.setText("");
		ctlNoMatch.setVisible(false);
		
		if(!ctlNameField.getText().isEmpty())
		{
			ResultSet rs = null;
	        PreparedStatement psSelect = null;
	        
			try
			{			
				String strName=ctlNameField.getText().toLowerCase();
				if(ctlIgnoreDiac.isSelected())
					strName=PaliUtil.ConvertDiac(strName);
				
				if(((SearchMode)ctlSearchMode.getSelectedItem()).getId()==1)				
		            strName='%'+strName+'%';				
				else							          
		            strName=strName+'%';				
				
				if(ctlIgnoreDiac.isSelected())
				{
		            psSelect=MainWindow.getDBConnection().prepareStatement("SELECT nodeid, nodetitle,FileID FROM nodes WHERE nodetitlenodiac LIKE ?");										
				}
				else
				{
					psSelect=MainWindow.getDBConnection().prepareStatement("SELECT nodeid, nodetitle,FileID FROM nodes WHERE LOWER(nodetitle) LIKE ?");										
				}
	            
	            psSelect.setString(1, strName);
				
	            rs = psSelect.executeQuery();
	            ArrayList<NodeInfo> arrFoundNodes=new ArrayList<NodeInfo>();
	            
	            while(rs.next()) 
	            {
	            	NodeInfo objNode=new NodeInfo(rs.getInt("nodeid"),rs.getString("nodetitle"),rs.getInt("FileID"));
	            	arrFoundNodes.add(objNode);	            	
	            }                            
	            
				ListModel ctlFoundNodesModel = 
					new DefaultComboBoxModel(arrFoundNodes.toArray());
				ctlFoundNodes.setModel(ctlFoundNodesModel);

				ctlNoMatch.setVisible(arrFoundNodes.isEmpty());
			}
			catch(SQLException sqle)
			{		
				SqlUtil.ReportSQLException(sqle);
			}
			catch(Exception ex)
			{		
				ex.printStackTrace();					
			}
			finally
			{
				SqlUtil.ClosePreparedStatement(psSelect);
				SqlUtil.CloseResultSet(rs);
			}
		}		
	}

	public int getNodeID() {
		int RetVal=0;
		
		if(ctlFoundNodes.getSelectedValue()!=null)
		{
			NodeInfo objNode=(NodeInfo)ctlFoundNodes.getSelectedValue();
			
			if(objNode.getFileID()!=0)
				RetVal=objNode.getNodeID();			
		}		
		
		return RetVal;
	}	
}
